package exer;

import bean.SensorReading;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;
import org.junit.Test;

import java.time.Duration;


public class temp_win_late {
    @Test
    public void test() throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
        SingleOutputStreamOperator<SensorReading> input = env.socketTextStream("node193", 9999)
                .map(new MapFunction<String, SensorReading>() {
                    @Override
                    public SensorReading map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new SensorReading(split[0], Long.parseLong(split[1]), Double.parseDouble(split[2]));
                    }
                });

        WatermarkStrategy<SensorReading> watermarkStrategy = WatermarkStrategy.<SensorReading>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                .withTimestampAssigner((SerializableTimestampAssigner<SensorReading>) (element, recordTimestamp) -> element.getTs() * 1000);

        SingleOutputStreamOperator<SensorReading> data = input.assignTimestampsAndWatermarks(watermarkStrategy)
                .keyBy(SensorReading::getId)
                .window(TumblingEventTimeWindows.of(Time.seconds(10), Time.seconds(5)))
                .allowedLateness(Time.seconds(2))
                .sideOutputLateData(new OutputTag<SensorReading>("late"){})
                .maxBy("temp");

        data.print("mainData");
        data.getSideOutput(new OutputTag<SensorReading>("late"){}).print("lateData");
        env.execute();
    }
}
